//Evt au redimensionnement
$(window).resize(function() {
	$('#map_canvas').css({
  		height: $(window).height() - $('[data-role="header"]').height() + "px",
  		width: $(window).width() + "px"
  	})
  	console.log('height : '+ $(window).height() - $('[data-role="header"]').height());
  	console.log('width : '+ $(window).width());
});

$(".page-map").on("pageshow", function (event) {
	console.log('page show event');
	$.mobile.showPageLoadingMsg();
	$("#popupInfoStation").popup();
	$('.menu').load('menu.html',function(){ $('#menu').panel(); $('#menu').panel('close'); });
	navigator.geolocation.getCurrentPosition(function(position){
		initializeGmap(position);
	}, function(){
		console.log('Erreur GPS, init avec ancienne position connue');
		if(lastPosition!=null){
			initializeGmap(lastPosition);
		}
	},{timeout:5000});
});




function initializeGmap(position) {
	lastPosition=position;
	
	var LatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	
  	map = new google.maps.Map(document.getElementById("map_canvas"), {
        zoom: 17,
        center: LatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  	
	
	google.maps.event.addListenerOnce(map, 'idle', function(){
		console.log('map charger ccompletement');
		$.mobile.hidePageLoadingMsg();
		$('#map_canvas').css({
			height: $(window).height() - $('[data-role="header"]').height() + "px",
			width: $(window).width() + "px"
		})
		google.maps.event.trigger(map, 'resize');
	});
  	
  	
  	console.log('height : '+ $('.page-map').height() - $('.page-map [data-role="header"]').height());
  	console.log('width : '+ $('.page-map').width());
  	
  	createCurentPosition(position); //Cree le marker de position
  	getStationsByCoord(position.coords.latitude, position.coords.longitude,10,addMarkers); //Affiche les 10 stations a proximite
  	
  	if(showUsersOnMap){
  		getUsersPositions(userID,addUsers);
  	}
  	
  	google.maps.event.trigger(map, 'resize');
  	
  	//Activation de la surveillance GPS
  	watchID = navigator.geolocation.watchPosition(updateGMap, errorGps, { enableHighAccuracy: true, timeout: 40000, maximumAge:50000, frequency: 60000}); 
    
  	
}

//Mise a jour de la position utilisateur + affichage des 10 stations a proximité de la position
function updateGMap(position){
	//Mise a jour du focus utilisateur
	currentPositionMarker.setPosition(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
	currentPositionCircle.set('center', new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
	currentPositionCircle.set('radius', position.coords.accuracy);
	
	console.log('Position utilisateur maj : '+new Date());
	
	//TODO : Suppression des anciens markers
	map.clearMarkersStations();
	map.clearMarkersUsers();
	
	//Affiche les 10 stations a proximite
  	getStationsByCoord(position.coords.latitude, position.coords.longitude,10,addMarkers);
  	//Enregistre la position, puis affiche les utilisateurs a proximité
  	if(sharePosition)
  		saveUserPosition(position.coords.latitude,position.coords.longitude,userID,sharePosition,positionIsSaved);
  	
  	google.maps.event.trigger(map, 'resize');
}
  	
function positionIsSaved(data){
	//Si la position de l'utilisateur a été enregistré en base, chargement de la nouvelle position des users
	if(data.success && showUsersOnMap){
		getUsersPositions(userID,addUsers);
	}else{
		console.log('Erreur lors de l\'enregistrement de la position de l\'utilisateur');
	}
}

//Callback erreur GeoLocalisation
function errorGps(){
	console.log('Erreur mise a jour position GPS : '+new Date());
}

//Creation du marqueur + cercle, representant la position de l'utilisateur actuel
function createCurentPosition(position){
	currentPositionMarker = new google.maps.Marker({
	    clickable: false,
	    cursor: 'pointer',
	    draggable: false,
	    flat: true,
	    icon: new google.maps.MarkerImage(
	        'img/position.png',
	        new google.maps.Size(23,22),
	        new google.maps.Point(0,0),
	        new google.maps.Point(11,11)),
	    optimized: false,
	    position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
	    title: 'Current location',
	    zIndex: 2,
	    map: map
	  });
	
	currentPositionCircle = new google.maps.Circle({
	  center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
	  radius: position.coords.accuracy,
	  map: map,
	  fillColor: '#61a0bf',
	  fillOpacity: 0.5,
	  strokeColor: '#1bb6ff',
	  strokeOpacity: 1.0,
	  strokeWeight: 1
	});
	map.fitBounds(currentPositionCircle.getBounds());
}

//Ajout des markers pour chaque station recu
function addMarkers(stations){
	markersStations = [];
	$(stations.markers).each( function(index,elem){
		var myMarker = new google.maps.Marker({
			icon: new google.maps.MarkerImage(
	        'img/pointer.png',
		        new google.maps.Size(26,36),
		        new google.maps.Point(0,0),
		        new google.maps.Point(7,7)),
	  		position: new google.maps.LatLng(elem.x, elem.y),
	  		//map: map,
	  		title: elem.nomStation
	  	});
		
		myMarker['data']=elem; //Ajout des données de la station dans le marker
	  	
		// Affichage de la fenetre au click sur le marker
		google.maps.event.addListener(myMarker, 'click', function() {
			//Affiche un loadingPage
			$.mobile.showPageLoadingMsg();
			
			//Ajout des infos
			$('#popupInfoStation h1.ui-title').html("Station");
			$('#popupInfoStation .content p').html("<span class='popupAdresse'><strong>Adresse</strong><br>"+$(this)[0].data.infoStation+"</span><span class='popupDistance'><strong>Distance</strong><br>"+parseInt($(this)[0].data.distance)+" mètres</span>");
			
			//Recupere les infos de la station
			getDisponibity($(this)[0].data.numStation,showInfoStation);
			
		});
		
		map.addMarkerStations(myMarker);
		//markersStations.push(myMarker);
	});
	
	console.log('Position stations maj : '+new Date());
}

//Ajout des markers Utilisateur (Vloveurs ayant partagé leur position)
function addUsers(data){
	markersUsers = [];
	$(data.array).each( function(index,elem){
		var myMarker = new google.maps.Marker({
	  		position: new google.maps.LatLng(elem.lat, elem.long),
	  		icon: new google.maps.MarkerImage(
	        'img/pointer.png',
		        new google.maps.Size(26,36),
		        new google.maps.Point(0,0),
		        new google.maps.Point(7,7)),
	  		//map: map,
	  		title: ""
	  	});
		
		map.addMarkerUsers(myMarker);
		//markersUsers.push(myMarker);
	})
}

//Affichage de la popup info d'une station 
function showInfoStation(data){
	/*$('#popupInfoStation .content p').append("<br>available : "+data.available);
	$('#popupInfoStation .content p').append("<br>connected : "+data.connected);
	$('#popupInfoStation .content p').append("<br>free : "+data.free);
	$('#popupInfoStation .content p').append("<br>open : "+data.open);
	$('#popupInfoStation .content p').append("<br>ticket : "+data.ticket);
	$('#popupInfoStation .content p').append("<br>total : "+data.total);
	$('#popupInfoStation .content p').append("<br>updated : "+data.updated);*/

	var open;
	if(data.open==1){
		open="Station ouverte";
	}
	else{
		open="Station fermée";
	}
	$('#popupInfoStation .content p').append("<span class='popupLibre'><strong>Velos disponibles</strong><br>"+data.available+"/"+data.total+" - "+open+"</span>");

	//Ouverture de la pop up d'info
	$("#popupInfoStation").popup('open');
	
	//Masque le loading page
	$.mobile.hidePageLoadingMsg();
}